package xyz.liuz.edb.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XMLToMap {
    public static void main(String[] args) throws DocumentException {
        String xml = "<Root><a>aaa</a><bc><b>bbb</b><c>ccc</c></bc><c>cccc</c></Root>";
        System.out.println(handle(xml));
    }

    public static Map<String, String> handle(String xml) throws DocumentException {
        Document doc =  DocumentHelper.parseText(xml);
        Map<String, String> map = new HashMap<String, String>();
        if (null == doc) {
            return map;
        }
        // 获取根元素
        Element rootElement = doc.getRootElement();
        recursionXmlToMap(rootElement,map);
        return map;
    }

    private static void recursionXmlToMap(Element element, Map<String, String> outmap) {
        // 得到根元素下的子元素列表
        List<Element> list = element.elements();
        int size = list.size();
        if (size == 0) {
            // 如果没有子元素,则将其存储进map中
            outmap.put(element.getName().toUpperCase(), element.getTextTrim().trim());
        } else {
            // 遍历子元素
            for(Element childElement:list) {
                recursionXmlToMap(childElement, outmap);
            }
        }
    }

}
